using System;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.SPOT;

namespace mfRCF.Core.Extensions
{
    public static class mfStreamExtensions
    {
        private const int C_INT_WAIT_CYCLE_MS = 300;
        /// <summary>
        /// waits until the length of the stream is not constant
        /// </summary>
        /// <param name="stream">stream to wait on</param>
        /// <param name="timeout">timeout, in ms</param>
        /// <returns>determines, if the timeout is exceed</returns>
        public static bool WaitUntilTransferIsCompleted(this Stream stream, int timeout)
        {
            if (!stream.CanRead)
            {
                throw new mfRcfException("ReadAllBytes: can't read on stream");
            }

            var checkRuntime = 0;
            long lengthBeforeWait = 0;
            long lengthAfterWait = 0;
            do
            {
                lengthBeforeWait = stream.Length;
                Thread.Sleep(C_INT_WAIT_CYCLE_MS);
                lengthAfterWait = stream.Length;

                checkRuntime += C_INT_WAIT_CYCLE_MS;

                if (checkRuntime >= timeout)
                    return true;

            } while (lengthBeforeWait != lengthAfterWait);

            return false;
        }

        public static byte[] ReadAllBytes(this Stream stream) 
        {
            if (!stream.CanRead)
            {
                throw new mfRcfException("ReadAllBytes: can't read on stream");
            }

            try
            {
                stream.Position = 0;
            }
            catch (NotSupportedException) 
            {
                Debug.Print("ReadAllBytes.Position setter is not supported"); 
            }

            var allBytes = new byte[stream.Length];

            stream.Read(allBytes, 0, (int)allBytes.Length);

            return allBytes;
        }

        public static string ReadAllText(this Stream stream)
        {
            var allBytes = stream.ReadAllBytes();

            char[] cc = System.Text.UTF8Encoding.UTF8.GetChars(allBytes);
            return new string(cc);
        }

        public static void WriteString(this Stream stream, string content)
        {
            var byteContent = System.Text.UTF8Encoding.UTF8.GetBytes(content);
            stream.Write(byteContent, 0, byteContent.Length);
        }

    }
}
